package com.opensource.component.dinging.configuration;

import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.util.StringUtils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * created by zhanglong and since  2019/12/27  10:09 下午
 *
 * @description: 描述
 */
@ConfigurationProperties(prefix = "opensource.component.dinging")
public class DingingProperties {

    private String dingingUrl = "https://oapi.dingtalk.com/robot/send";

    private String accessToken;

    private String secretKey;

    private static final String SECRET_TYPE = "HmacSHA256";

    private static final String CHARSET_UTF8 = "UTF-8";

    public String getDingingUrl() {
        if (StringUtils.isEmpty(dingingUrl)) {
            throw new NullPointerException("dingingUrl could not be blank");
        }
        StringBuilder url = new StringBuilder(dingingUrl)
                .append("?access_token=").append(getAccessToken());
        if (!StringUtils.isEmpty(secretKey)) {
            try {
                signSecret(url, secretKey);
            } catch (NoSuchAlgorithmException | UnsupportedEncodingException | InvalidKeyException e) {
                throw new IllegalArgumentException("sign secret exception");
            }
        }
        return url.toString();
    }

    public void setDingingUrl(String dingingUrl) {
        this.dingingUrl = dingingUrl;
    }

    public String getAccessToken() {
        if (StringUtils.isEmpty(accessToken)) {
            throw new NullPointerException(
                    "access_tokens must be at least of one value, more is split by ','");
        }
        return accessToken;
    }

    public void setAccessToken(String accessToken) {
        this.accessToken = accessToken;
    }

    public void setSecretKey(String secretKey) {
        this.secretKey = secretKey;
    }

    private void signSecret(StringBuilder url, String secret)
            throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException {
        long timestamp = System.currentTimeMillis();
        String stringToSign = timestamp + "\n" + secret;
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
        byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
        final String signSecret = URLEncoder.encode(new String(Base64.encodeBase64(signData)),"UTF-8");
        url.append("&timestamp=").append(timestamp).append("&sign=").append(signSecret);
    }

//    timestamp = long(round(time.time() * 1000))
//    secret = 'this is secret'
//    secret_enc = bytes(secret).encode('utf-8')
//    string_to_sign = '{}\n{}'.format(timestamp, secret)
//    string_to_sign_enc = bytes(string_to_sign).encode('utf-8')
//    hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
//    sign = urllib.quote_plus(base64.b64encode(hmac_code))
//    print(timestamp)
//    print(sign)
}
